<template>
  <div>
    <ALayoutHeader class="detail-header">
      <div class="erp-row-item-center">
        <div class="erp-row-item-center" style="cursor: pointer" @click="emit('switch')">
          <icon-left size="22" class="erp-mr-6" />
          <span class="erp-font-size-16">返回</span>
        </div>
        <ADivider direction="vertical"></ADivider>
        <span class="erp-font-size-16">
          {{ dayjs(payrollInfo.payrollMonth).format('YYYY年MM月工资表') }}
        </span>
      </div>
      <div></div>
    </ALayoutHeader>
    <ALayoutContent>
      <AForm :model="searchFrom" class="erp-search-form">
        <ARow class="grid-demo" :gutter="10">
          <ACol :span="6">
            <AFormItem hide-label content-class="">
              <AInput v-model="searchFrom.employeeName" placeholder="员工姓名" allow-clear />
            </AFormItem>
          </ACol>
          <ACol :span="6">
            <AFormItem hide-label>
              <ASelect v-model="searchFrom.status" placeholder="状态" allow-clear>
                <AOption label="已发放" :value="1"></AOption>
                <AOption label="未发放" :value="0"></AOption>
              </ASelect>
            </AFormItem>
          </ACol>
        </ARow>
      </AForm>
      <ACard>
        <div class="erp-mb-10 w100 erp-search-btn-box">
          <ASpace>
            <AButton type="primary" @click="onSearch">
              <template #icon>
                <icon-search />
              </template>
            </AButton>
            <ATooltip content="清空筛选项" position="top">
              <AButton type="dashed" @click="onReset">
                <template #icon>
                  <icon-refresh />
                </template>
              </AButton>
            </ATooltip>
            <AButton type="outline" @click="openEdit('新增')">新增</AButton>
            <AButton
              type="outline"
              status="normal"
              :loading="tableBtnLoad.batch"
              @click="tableBtn('batch')"
            >
              批量确认发放
            </AButton>
          </ASpace>
          <ASpace> </ASpace>
        </div>
        <ATable
          v-model:selected-keys="selectedKeys"
          :pagination="false"
          :data="tableData"
          :bordered="{ cell: true }"
          :span-method="spanMethod"
          column-resizable
          size="small"
          :row-selection="rowSelection"
          row-key="payrollId"
        >
          <template #columns>
            <ATableColumn title="姓名" data-index="employeeName" :width="160"> </ATableColumn>
            <ATableColumn title="基本工资" data-index="baseSalaryAmt" :width="100" align="right">
              <template #cell="{ record }">
                {{ `¥${formatPrice(record.baseSalaryAmt)}` }}
              </template>
            </ATableColumn>
            <ATableColumn
              title="销售提成"
              data-index="saleCommissionAmt"
              :width="100"
              align="right"
            >
              <template #cell="{ record }">
                <!-- <div v-if="isEmpty(record.detailList)">0</div>
                <ALink v-else @click="rowEvent(record, 'open-bill')">
                  {{ `¥${formatPrice(record.saleCommissionAmt)}` }}
                </ALink> -->
                <div>{{ `¥${formatPrice(record.saleCommissionAmt)}` }}</div>
              </template>
            </ATableColumn>
            <ATableColumn
              title="计件提成"
              data-index="pieceCommissionAmt"
              :width="120"
              align="right"
            >
              <template #cell="{ record }">
                {{ `¥${formatPrice(record.pieceCommissionAmt)}` }}
              </template>
            </ATableColumn>
            <ATableColumn
              title="送货提成"
              data-index="deliveryOmmissionAmt"
              :width="100"
              align="right"
            >
              <template #cell="{ record }">
                {{ `¥${formatPrice(record.deliveryOmmissionAmt)}` }}
              </template>
            </ATableColumn>
            <ATableColumn title="其他" data-index="otherAmt" :width="90" align="right">
              <template #cell="{ record }">
                {{ `¥${formatPrice(record.otherAmt)}` }}
              </template>
            </ATableColumn>
            <ATableColumn title="加班" data-index="overtimeAmt" :width="100" align="right">
              <template #cell="{ record }">
                {{ `¥${formatPrice(record.overtimeAmt)}` }}
              </template>
            </ATableColumn>
            <ATableColumn title="考勤奖" data-index="attendanceAmt" :width="100" align="right">
              <template #cell="{ record }">
                {{ `¥${formatPrice(record.attendanceAmt)}` }}
              </template>
            </ATableColumn>
            <ATableColumn title="支取" data-index="expendAmt" :width="90" align="right">
              <template #cell="{ record }">
                {{ `¥${formatPrice(record.expendAmt)}` }}
              </template>
            </ATableColumn>
            <ATableColumn title="合计" data-index="totalAmt" :width="90" align="right">
              <template #cell="{ record }">
                {{ `¥${formatPrice(record.totalAmt)}` }}
              </template>
            </ATableColumn>
            <ATableColumn title="状态" data-index="status" :width="80" align="center">
              <template #cell="{ record }">
                {{ record.status ? '已发放' : '未发放' }}
              </template>
            </ATableColumn>
            <ATableColumn title="附件" data-index="paymentMethod" :width="90" align="center">
              <template #cell="{ record }">
                <ADropdown
                  v-if="!isEmpty(record.fileList)"
                  @select="(fileUrl: any) => openFlie(record, fileUrl)"
                >
                  <ALink>{{ record.fileList.length }}</ALink>
                  <template #content>
                    <ADoption
                      v-for="(item, index) in record.fileList"
                      :key="index"
                      :value="item.fileUrl"
                    >
                      {{ item.fileName }}
                    </ADoption>
                  </template>
                </ADropdown>
              </template>
            </ATableColumn>
            <ATableColumn title="备注" data-index="remark" :width="200"> </ATableColumn>
            <ATableColumn title="操作" :width="145" align="center" fixed="right">
              <template #cell="{ record }">
                <ASpace>
                  <AButton type="primary" size="mini" @click="rowEvent(record, 'edit')">
                    修改
                  </AButton>
                  <AButton status="danger" size="mini" @click="rowEvent(record, 'del')">
                    删除
                  </AButton>
                </ASpace>
              </template>
            </ATableColumn>
          </template>
        </ATable>
        <div class="arco-table-pagination">
          <APagination
            :total="pageParam.totalCount"
            :page-size="pageParam.pageSize"
            show-total
            @change="(page: number) => tableEvent('page-change', page)"
          />
        </div>
      </ACard>
    </ALayoutContent>

    <EditPopupForm
      v-if="props.payrollInfo.payrollId"
      v-model:visible="editModal"
      :title="editModalTitle"
      :check-data="rowData"
      :payroll-id="props.payrollInfo.payrollId"
      @reload="getTableData"
    ></EditPopupForm>
  </div>
</template>

<script lang="ts" setup>
import {
  delSalarySheetDetail,
  getSalarySheetDetailPageList,
  payrollMemberBatchGive,
  SalarySheetDetailResItem,
  SalarySheetDetailSearch,
  SalarySheetResItem
} from '@renderer/api/salarySheet'
import EditPopupForm from './editPopupForm.vue'
import { Message, Modal, TableRowSelection } from '@arco-design/web-vue'
import { downloadByteFile, formatPrice } from '@renderer/utils/mixins'
import { isEmpty } from 'lodash-es'
import dayjs from 'dayjs'

const props = defineProps({
  payrollInfo: {
    type: Object as PropType<SalarySheetResItem>,
    default: () => {
      return {}
    }
  }
})
const emit = defineEmits(['switch'])
const searchFrom = ref<SalarySheetDetailSearch>({
  payrollId: '',
  employeeName: '',
  status: ''
})
const editModal = ref(false)
const editModalTitle = ref('新增')
const tableData = ref<SalarySheetDetailResItem[]>([])
const pageParam = reactive({
  currentPage: 1,
  pageSize: 20,
  totalCount: 0
})
const selectedKeys = ref<string[]>([])
const rowSelection = reactive<TableRowSelection>({
  type: 'checkbox',
  showCheckedAll: true
})
const tableBtnLoad = ref({
  batch: false
})

watch(
  () => props.payrollInfo,
  (newValue) => {
    if (!isEmpty(newValue)) {
      searchFrom.value.payrollId = newValue.payrollId
      getTableData()
    }
  },
  { immediate: true, deep: true }
)

async function getTableData() {
  const res = await getSalarySheetDetailPageList({ ...searchFrom.value, ...pageParam })
  tableData.value = res.data.list
  pageParam.totalCount = res.data.totalCount!
}

const onSearch = () => {
  pageParam.currentPage = 1
  getTableData()
}
function onReset() {
  searchFrom.value = {
    payrollId: props.payrollInfo.payrollId,
    employeeName: '',
    status: ''
  }
  pageParam.currentPage = 1
  pageParam.pageSize = 20
  getTableData()
}

function tableEvent(type: 'page-change', param: any) {
  switch (type) {
    case 'page-change':
      pageParam.currentPage = param
      getTableData()
      break

    default:
      break
  }
}
const spanMethod = ({ record, columnIndex }) => {
  if (columnIndex < 2) {
    if (record.span) {
      return {
        colspan: 1,
        rowspan: record.span
      }
    }
  }
}

function openEdit(title: string) {
  rowData.value = {}
  editModalTitle.value = title
  editModal.value = true
}

const rowData = ref({})
function rowEvent(row: SalarySheetDetailResItem, type: string) {
  switch (type) {
    case 'del':
      Modal.warning({
        title: '警告',
        content: '当前数据删除后不可恢复，是否继续？',
        okText: '确认',
        cancelText: '取消',
        simple: false,
        hideCancel: false,
        maskClosable: false,
        closable: false,
        onOk: () => {
          delSalarySheetDetail({ payrollMemberId: row.payrollMemberId! }).then(() => {
            Message.success('删除成功')
            getTableData()
          })
        },
        onCancel: () => {}
      })
      break
    case 'copy':
      rowData.value = row
      editModalTitle.value = '新增'
      editModal.value = true
      break
    case 'edit':
      rowData.value = row
      editModalTitle.value = '修改'
      editModal.value = true
      break
    // case 'open-bill':
    //   deliveryBills.value = row.detailList
    //   deliveryBillShow.value = true
    //   break

    default:
      break
  }
}

const openFlie = (record: SalarySheetDetailResItem, flieUrl: string) => {
  const temp = record.fileList.find((item) => item.fileUrl === flieUrl)
  if (temp) {
    downloadByteFile(temp)
  }
}
function tableBtn(type: 'batch') {
  switch (type) {
    case 'batch':
      tableBtnLoad.value.batch = true
      payrollMemberBatchGive({
        payrollId: searchFrom.value.payrollId,
        idList: selectedKeys.value
      })
        .then(() => {
          Message.success('批量发放成功')
          getTableData()
        })
        .finally(() => {
          tableBtnLoad.value.batch = false
        })
      break

    default:
      break
  }
}
</script>
<style lang="less" scoped>
.erp-search-btn-box {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.detail-header {
  padding: 10px;
  background-color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid var(--color-border-4);
}
</style>
